package com.waikuai.shop.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.waikuai.shop.entity.Product;
import com.waikuai.shop.entity.ShoppingCart;
import com.waikuai.shop.mapper.ProductMapper;
import com.waikuai.shop.mapper.ShoppingCartMapper;
import com.waikuai.shop.service.ShoppingCartService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * 购物车服务实现类
 * @author waikuai
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class ShoppingCartServiceImpl extends ServiceImpl<ShoppingCartMapper, ShoppingCart>
        implements ShoppingCartService {

    private final ShoppingCartMapper shoppingCartMapper;
    private final ProductMapper productMapper;

    @Override
    public List<ShoppingCart> getUserCart(Long userId) {
        try {
            return shoppingCartMapper.selectCartItemsByUserId(userId);
        } catch (Exception e) {
            log.error("获取用户购物车列表失败，用户ID: {}", userId, e);
            return new ArrayList<>();
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean addToCart(Long userId, Long productId, Integer quantity) {
        try {
            if (quantity <= 0) {
                log.warn("添加购物车数量必须大于0，用户ID: {}, 商品ID: {}, 数量: {}", userId, productId, quantity);
                return false;
            }

            // 检查商品是否存在
            Product product = productMapper.selectById(productId);
            if (product == null || product.getStatus() == null || product.getStatus() != 1) {
                log.warn("商品不存在或已下架，商品ID: {}", productId);
                return false;
            }

            // 检查库存字段是否为null
            if (product.getStockQuantity() == null) {
                log.warn("商品库存信息异常，商品ID: {}, 库存为null", productId);
                return false;
            }

            // 先检查购物车中是否已存在该商品（包括已删除的记录）
            ShoppingCart existingItem = shoppingCartMapper.selectByUserIdAndProductIdIncludeDeleted(userId, productId);
            
            // 计算最终需要的数量
            int finalQuantity;
            if (existingItem != null && (existingItem.getDeleted() == null || existingItem.getDeleted() == 0)) {
                // 如果购物车中已有未删除的记录，计算总数量
                int existingQuantity = existingItem.getQuantity() != null ? existingItem.getQuantity() : 0;
                finalQuantity = existingQuantity + quantity;
            } else {
                // 如果是新添加或恢复已删除的记录，使用新数量
                finalQuantity = quantity;
            }

            // 检查库存是否足够
            if (product.getStockQuantity() < finalQuantity) {
                log.warn("商品库存不足，商品ID: {}, 库存: {}, 需要数量: {}, 购物车已有数量: {}", 
                        productId, product.getStockQuantity(), finalQuantity,
                        existingItem != null && existingItem.getDeleted() != null && existingItem.getDeleted() == 0 
                            ? existingItem.getQuantity() : 0);
                return false;
            }

            // 执行添加或更新操作
            if (existingItem != null) {
                // 如果记录存在但已被逻辑删除，恢复它
                if (existingItem.getDeleted() != null && existingItem.getDeleted() == 1) {
                    log.info("发现已删除的购物车记录，恢复并更新，用户ID: {}, 商品ID: {}", userId, productId);
                    
                    // 直接修改对象并使用updateById，这样可以更新已删除的记录
                    existingItem.setDeleted(0);  // 恢复记录
                    existingItem.setQuantity(quantity);
                    existingItem.setSelected(1);
                    
                    // 使用自定义的mapper方法来更新，绕过逻辑删除的限制
                    int result = shoppingCartMapper.updateIncludeDeleted(existingItem);

                    if (result > 0) {
                        log.info("恢复购物车商品成功，用户ID: {}, 商品ID: {}, 数量: {}", userId, productId, quantity);
                        return true;
                    }
                } else {
                    // 记录存在且未删除，更新数量
                    LambdaUpdateWrapper<ShoppingCart> updateWrapper = new LambdaUpdateWrapper<>();
                    updateWrapper.eq(ShoppingCart::getId, existingItem.getId())
                                 .set(ShoppingCart::getQuantity, finalQuantity);
                    int result = shoppingCartMapper.update(null, updateWrapper);

                    if (result > 0) {
                        log.info("更新购物车商品数量成功，用户ID: {}, 商品ID: {}, 新数量: {}", userId, productId, finalQuantity);
                        return true;
                    }
                }
            } else {
                // 不存在记录，新增购物车项
                ShoppingCart cartItem = new ShoppingCart();
                cartItem.setUserId(userId);
                cartItem.setProductId(productId);
                cartItem.setQuantity(quantity);
                cartItem.setSelected(1);

                int result = shoppingCartMapper.insert(cartItem);
                if (result > 0) {
                    log.info("添加商品到购物车成功，用户ID: {}, 商品ID: {}, 数量: {}", userId, productId, quantity);
                    return true;
                }
            }

            return false;
        } catch (Exception e) {
            log.error("添加商品到购物车失败，用户ID: {}, 商品ID: {}, 数量: {}", userId, productId, quantity, e);
            throw new RuntimeException("添加商品到购物车失败");
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateCartItemQuantity(Long userId, Long productId, Integer quantity) {
        try {
            if (quantity <= 0) {
                log.warn("更新购物车数量必须大于0，用户ID: {}, 商品ID: {}, 数量: {}", userId, productId, quantity);
                return false;
            }

            // 检查商品库存
            Product product = productMapper.selectById(productId);
            if (product == null || product.getStockQuantity() < quantity) {
                log.warn("商品库存不足，商品ID: {}, 库存: {}, 购买数量: {}", productId, product.getStockQuantity(), quantity);
                return false;
            }

            LambdaUpdateWrapper<ShoppingCart> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.eq(ShoppingCart::getUserId, userId)
                         .eq(ShoppingCart::getProductId, productId)
                         .set(ShoppingCart::getQuantity, quantity);

            int result = shoppingCartMapper.update(null, updateWrapper);
            if (result > 0) {
                log.info("更新购物车商品数量成功，用户ID: {}, 商品ID: {}, 新数量: {}", userId, productId, quantity);
                return true;
            }

            return false;
        } catch (Exception e) {
            log.error("更新购物车商品数量失败，用户ID: {}, 商品ID: {}, 数量: {}", userId, productId, quantity, e);
            throw new RuntimeException("更新购物车商品数量失败");
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean removeFromCart(Long userId, Long productId) {
        try {
            log.info("开始删除购物车商品，用户ID: {}, 商品ID: {}", userId, productId);
            
            // 使用MyBatis-Plus的查询方法，确保逻辑删除的一致性
            LambdaQueryWrapper<ShoppingCart> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(ShoppingCart::getUserId, userId)
                        .eq(ShoppingCart::getProductId, productId);
            
            // 先查询确认记录是否存在（用于调试）
            ShoppingCart existingItem = shoppingCartMapper.selectOne(queryWrapper);
            if (existingItem != null) {
                log.info("查询到购物车记录，ID: {}, 用户ID: {}, 商品ID: {}, 数量: {}", 
                        existingItem.getId(), existingItem.getUserId(), existingItem.getProductId(), existingItem.getQuantity());
            } else {
                log.warn("查询购物车记录不存在，用户ID: {}, 商品ID: {}", userId, productId);
            }

            // 使用MyBatis-Plus的delete方法，会自动处理逻辑删除
            int result = shoppingCartMapper.delete(queryWrapper);
            if (result > 0) {
                log.info("删除购物车商品成功，用户ID: {}, 商品ID: {}, 删除记录数: {}", userId, productId, result);
                return true;
            }

            log.warn("删除购物车商品失败，删除记录数为0，用户ID: {}, 商品ID: {}", userId, productId);
            // 如果查询到了记录但删除失败，记录更详细的警告
            if (existingItem != null) {
                log.error("警告：查询到购物车记录但删除失败，可能存在数据不一致问题，记录ID: {}", existingItem.getId());
            }
            return false;
        } catch (Exception e) {
            log.error("删除购物车商品发生异常，用户ID: {}, 商品ID: {}, 异常类型: {}, 异常消息: {}", 
                    userId, productId, e.getClass().getSimpleName(), e.getMessage(), e);
            throw new RuntimeException("删除购物车商品失败: " + e.getMessage(), e);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean batchRemoveFromCart(Long userId, List<Long> productIds) {
        try {
            if (productIds == null || productIds.isEmpty()) {
                return true;
            }

            LambdaQueryWrapper<ShoppingCart> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(ShoppingCart::getUserId, userId)
                        .in(ShoppingCart::getProductId, productIds);

            int result = shoppingCartMapper.delete(queryWrapper);
            if (result > 0) {
                log.info("批量删除购物车商品成功，用户ID: {}, 删除数量: {}", userId, result);
                return true;
            }

            return false;
        } catch (Exception e) {
            log.error("批量删除购物车商品失败，用户ID: {}", userId, e);
            throw new RuntimeException("批量删除购物车商品失败");
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean clearCart(Long userId) {
        try {
            int result = shoppingCartMapper.clearCartByUserId(userId);
            if (result > 0) {
                log.info("清空购物车成功，用户ID: {}, 清空数量: {}", userId, result);
                return true;
            }

            return false;
        } catch (Exception e) {
            log.error("清空购物车失败，用户ID: {}", userId, e);
            throw new RuntimeException("清空购物车失败");
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateSelectedStatus(Long userId, Long productId, Boolean selected) {
        try {
            int status = selected ? 1 : 0;
            int result = shoppingCartMapper.updateSelectedStatus(userId, productId, status);
            if (result > 0) {
                log.info("更新购物车商品选中状态成功，用户ID: {}, 商品ID: {}, 选中状态: {}", userId, productId, selected);
                return true;
            }

            return false;
        } catch (Exception e) {
            log.error("更新购物车商品选中状态失败，用户ID: {}, 商品ID: {}", userId, productId, e);
            throw new RuntimeException("更新购物车商品选中状态失败");
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateAllSelectedStatus(Long userId, Boolean selected) {
        try {
            int status = selected ? 1 : 0;
            int result = shoppingCartMapper.updateAllSelectedStatus(userId, status);
            if (result > 0) {
                log.info("更新购物车商品选中状态成功，用户ID: {}, 选中状态: {}, 更新数量: {}", userId, selected, result);
                return true;
            }

            return false;
        } catch (Exception e) {
            log.error("更新购物车商品选中状态失败，用户ID: {}", userId, e);
            throw new RuntimeException("更新购物车商品选中状态失败");
        }
    }

    @Override
    public List<ShoppingCart> getSelectedItems(Long userId) {
        try {
            return shoppingCartMapper.selectSelectedItemsByUserId(userId);
        } catch (Exception e) {
            log.error("获取用户选中的购物车商品失败，用户ID: {}", userId, e);
            return new ArrayList<>();
        }
    }

    @Override
    public BigDecimal calculateSelectedTotal(Long userId) {
        try {
            List<ShoppingCart> selectedItems = getSelectedItems(userId);
            BigDecimal total = BigDecimal.ZERO;

            for (ShoppingCart item : selectedItems) {
                if (item.getProduct() != null && item.getProduct().getPrice() != null) {
                    BigDecimal itemTotal = item.getProduct().getPrice().multiply(new BigDecimal(item.getQuantity()));
                    total = total.add(itemTotal);
                }
            }

            return total;
        } catch (Exception e) {
            log.error("计算选中商品总金额失败，用户ID: {}", userId, e);
            return BigDecimal.ZERO;
        }
    }

    @Override
    public Integer countCartItems(Long userId) {
        try {
            return shoppingCartMapper.countCartItems(userId);
        } catch (Exception e) {
            log.error("统计用户购物车商品数量失败，用户ID: {}", userId, e);
            return 0;
        }
    }

    @Override
    public boolean isInCart(Long userId, Long productId) {
        try {
            ShoppingCart cartItem = shoppingCartMapper.selectByUserIdAndProductId(userId, productId);
            return cartItem != null;
        } catch (Exception e) {
            log.error("检查商品是否在购物车中失败，用户ID: {}, 商品ID: {}", userId, productId, e);
            return false;
        }
    }

    @Override
    public Integer getCartItemQuantity(Long userId, Long productId) {
        try {
            ShoppingCart cartItem = shoppingCartMapper.selectByUserIdAndProductId(userId, productId);
            return cartItem != null ? cartItem.getQuantity() : 0;
        } catch (Exception e) {
            log.error("获取购物车商品数量失败，用户ID: {}, 商品ID: {}", userId, productId, e);
            return 0;
        }
    }

    @Override
    public boolean validateCartStock(Long userId) {
        try {
            List<ShoppingCart> cartItems = getUserCart(userId);
            for (ShoppingCart item : cartItems) {
                if (item.getProduct() != null && item.getProduct().getStockQuantity() < item.getQuantity()) {
                    log.warn("购物车商品库存不足，商品ID: {}, 库存: {}, 购买数量: {}",
                            item.getProductId(), item.getProduct().getStockQuantity(), item.getQuantity());
                    return false;
                }
            }
            return true;
        } catch (Exception e) {
            log.error("验证购物车商品库存失败，用户ID: {}", userId, e);
            return false;
        }
    }

    @Override
    public List<Product> getOutOfStockItems(Long userId) {
        try {
            List<ShoppingCart> cartItems = getUserCart(userId);
            List<Product> outOfStockItems = new ArrayList<>();

            for (ShoppingCart item : cartItems) {
                if (item.getProduct() != null && item.getProduct().getStockQuantity() < item.getQuantity()) {
                    outOfStockItems.add(item.getProduct());
                }
            }

            return outOfStockItems;
        } catch (Exception e) {
            log.error("获取库存不足的商品列表失败，用户ID: {}", userId, e);
            return new ArrayList<>();
        }
    }

    @Override
    public ShoppingCart getByUserIdAndProductId(Long userId, Long productId) {
        try {
            return shoppingCartMapper.selectByUserIdAndProductId(userId, productId);
        } catch (Exception e) {
            log.error("根据用户ID和商品ID查询购物车记录失败，用户ID: {}, 商品ID: {}", userId, productId, e);
            return null;
        }
    }
}